﻿/*
   Copyright 2012 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Flower.Workflow;
using System.Runtime.Serialization;
using Sample.DataContracts;

namespace Sample.Workflows
{
    [Path("FlowerSamples")]
    [AllowStartTo("Application")]
    [AllowStartTo("Processor")]
    [DataContract]
    public class BubbleSort : Process, IWorkflow<BubbleSortRequest, object>
    {
        [DataMember]
        private int i;

        [DataMember]
        private int tmp;

        [DataMember]
        private bool swapped;

        [DataMember]
        private int[] array;

        public object Initialize(IInitializationContext context, BubbleSortRequest arg)
        {
            array = new int[arg.ArraySize];

            var rnd = new Random();
            for (int j = 0; j < array.Length; j++)
            {
                array[j] = rnd.Next(100);
            }

            return null;
        }

        public void DefineLocalSets(ISetsBuilder bld)
        {
            
        }

        public void DefineProcess(IProcessBuilder bld)
        {
            bld
                .While(_ => true)
                    .Exec(_ => { swapped = false; })

                    .For(_ => { i = 0; }, _ => i < array.Length, _ => { i++; })
                        .If(_ => array[i] > array[i + 1])
                            .Exec(_ => { tmp = array[i]; })
                            .Exec(_ => { array[i] = array[i + 1]; })
                            .Exec(_ => { array[i + 1] = tmp; })

                            .Exec(_ => { swapped = true; })
                        .End()
                    .End()

                    .If(_ => !swapped)
                        .Break()
                    .End()
                .End();
        }
    }
}
